package main

import (
	"encoding/json"
	"fmt"
)

/*
*
为属性增加tag
*/
type Cat struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Color string
	Hobby string
	/* 指针类型 */
	Ptr *int
	// 切片
	Slice []int
	/* map */
	Map1 map[string]string
}

/* 增加一个方法,此处是变量的副本,内部的修改不会影响外面  */
func (this Cat) getName() string {
	this.Name = "临时"
	fmt.Println("getName方法被调用,this.name=", this.Name)
	return this.Name
}

/*
此处为指针传递
*/
func (this *Cat) getName2() string {
	this.Name = "临时"
	fmt.Println("getName方法被调用,this.name=", this.Name)
	return this.Name
}

/*
*
相当于toString
*/
func (this *Cat) String() string {
	fmt.Println("String方法被调用")
	return fmt.Sprintf("Cat{Name: %s, Age: %d, Color: %s, Hobby: %s}", this.Name, this.Age, this.Color, this.Hobby)
}

/*
*
看到第270页
*/
func main() {
	var cat1 Cat
	cat1.Name = "Tom"
	cat1.Age = 3
	cat1.Color = "Blue"
	cat1.Hobby = "Play"

	jsonStr, error := json.Marshal(cat1)
	if error != nil {
		fmt.Println("Error  json", error)
	}
	/* json格式化 */
	fmt.Println("JSON String:", string(jsonStr))

	catName := cat1.getName()
	fmt.Println("Cat Name:", catName)
	fmt.Println("Cat Name:", cat1.Name)

	catName = cat1.getName2()
	fmt.Println("Cat Name:", catName)
	fmt.Println("Cat Name:", cat1.Name)

	fmt.Println("cat1 toString1:", cat1)
	/* 默认调用String方法 */
	fmt.Println("cat1 toString2:", &cat1)
}
